#include "head.h"
//1.判断存不存在
//2.判断是文件还是目录
//3.判断目录是否为空
//4.删除空目录
int rmdirFunc(const int cur_dir_id,const char* dirname,char *error_buf)
{
    MYSQL* mysql=mysql_init(NULL);
    MYSQL* ret=mysql_real_connect(mysql,"localhost","root","123","os",0,NULL,0);
    if(ret==NULL)
    {
        sprintf(error_buf,"%s:%s","mysql_real_connect",mysql_error(mysql));
        return -1;
    }

    char sql[500]={0};

    sprintf(sql,"select id,type from vft where parent_id=%d and filename='%s'; ",cur_dir_id,dirname);
    /* printf("sql=%s\n",sql); */
    int qret=mysql_query(mysql,sql);
    if(qret!=0)
    {
        sprintf(error_buf,"%s:%s","mysql_query",mysql_error(mysql));
        return -1;
    }

    MYSQL_RES* rows=mysql_store_result(mysql);
    if(mysql_num_rows(rows)==0)
    {
        //不存在
        strcpy(error_buf,"not exit dirname!");
        /* printf("not exit dirname!\n"); */
        return -1;
    }
    //存在，判断是file还是dir
    for(unsigned i=0;i<mysql_num_rows(rows);++i)
    {
        MYSQL_ROW row=mysql_fetch_row(rows);
        if(strcmp("d",row[1]))
        {
            //不是目录
            strcpy(error_buf,"is not dir!");
            /* printf("is not dir!\n"); */
            return -1;
        }
        else
        {
            //是目录
            int id=atoi(row[0]);
            bzero(sql,sizeof(sql));
            sprintf(sql,"select id from vft where parent_id=%d;",id);
            /* printf("sql=%s\n",sql); */
            qret=mysql_query(mysql,sql);
            if(qret!=0)
            {
                sprintf(error_buf,"%s:%s","mysql_query",mysql_error(mysql));
                return -1;
            }
            MYSQL_RES *rows1=mysql_store_result(mysql);
           /* printf("%ld\n",mysql_num_rows(rows1)); */
            if(mysql_num_rows(rows1)>0)
            {
                //目录不空
                strcpy(error_buf,"dir is not empty!");
                /* printf("dir is not empty!\n"); */
                return -1;
            }
            else
            {
                //目录为空
                /* printf("3\n"); */
                bzero(sql,sizeof(sql));
                sprintf(sql,"delete from vft where id=%d;",id);
                /* printf("sql=%s\n",sql); */
                qret=mysql_query(mysql,sql);
                /* printf("4\n"); */
                if(qret!=0)
                {
                    sprintf(error_buf,"%s:%s","mysql_query",mysql_error(mysql));
                    return -1;
                }
                printf("rmdir success!\n");
            }
        }
    }
    /* printf("\n"); */
    mysql_close(mysql);
    return 0;
}
